package com.biz.primus.model.tms.vo;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
 * 百度鹰眼
 * Created by dylan on 17-1-13.
 */
public class YingyanUtil {
    private static Logger logger = LoggerFactory.getLogger(YingyanUtil.class);
    private static final RestTemplate restTemplate = new RestTemplate();
    public static String addUrl = "http://api.map.baidu.com/trace/v2/entity/add"; //添加entity url
    private static String snAddUrl = "/trace/v2/entity/add?";  //post请求su签名参数
    private static String gethistoryUrl = "http://api.map.baidu.com/trace/v2/track/gethistory?"; //查询轨迹地址
    private static String snGethistoryUrl = "/trace/v2/track/gethistory?";  //post请求su签名参数
    private static String getMapUrl = "http://api.map.baidu.com/staticimage/v2?"; //百度静态地图获取地址


    private static String ak;
    private static String sk;
    private static String serviceId;
    private static String mapAk;

    /**
     * 生成轨迹图片url
     */
    public static List<LongitudeAndLatitudeVo> getMapUrl(String entity_name, Long start_time, Long end_time) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(entity_name) || start_time == null || end_time == null) {
            logger.info("查询轨迹图片有异常参数：{},{},{}", entity_name, start_time, end_time);
            return newArrayList();
        }
        YingyanHistoryVo yingyanHistoryVo = getHistory(entity_name, start_time, end_time);
        if (yingyanHistoryVo.getStatus() != 0) {
            logger.info("鹰眼返回错误提示status:{},msg:{}", yingyanHistoryVo.getStatus(), yingyanHistoryVo.getMessage());
            return newArrayList();
        }
        StartAndEndPointVo startPoint = yingyanHistoryVo.getStart_point();
        StartAndEndPointVo endPointPoint = yingyanHistoryVo.getEnd_point();
        List<PointVo> pointVos = yingyanHistoryVo.getPoints();
        List<LongitudeAndLatitudeVo> longitudeAndLatitudeVos = newArrayList();
        if (startPoint != null && endPointPoint != null && CollectionUtils.isNotEmpty(pointVos)) {
            LongitudeAndLatitudeVo endLongitudeAndLatitudeVo = new LongitudeAndLatitudeVo();
            endLongitudeAndLatitudeVo.setLongitude(endPointPoint.getLongitude().toString());
            endLongitudeAndLatitudeVo.setLatitude(endPointPoint.getLatitude().toString());
            longitudeAndLatitudeVos.add(endLongitudeAndLatitudeVo);
            for (PointVo pointVo : pointVos) {
                LongitudeAndLatitudeVo longitudeAndLatitudeVo = new LongitudeAndLatitudeVo();
                String[] location = pointVo.getLocation();
                if (location != null && location.length != 0) {
                    for (int i = 0; i < location.length; i++) {
                        if (i == 0) {
                            longitudeAndLatitudeVo.setLongitude(location[i]);
                        } else {
                            longitudeAndLatitudeVo.setLatitude(location[i]);
                        }
                    }
                }
                longitudeAndLatitudeVos.add(longitudeAndLatitudeVo);
            }
            LongitudeAndLatitudeVo startLongitudeAndLatitudeVo = new LongitudeAndLatitudeVo();
            startLongitudeAndLatitudeVo.setLongitude(startPoint.getLongitude().toString());
            startLongitudeAndLatitudeVo.setLatitude(startPoint.getLatitude().toString());
            longitudeAndLatitudeVos.add(startLongitudeAndLatitudeVo);

            return longitudeAndLatitudeVos;
        }
        return newArrayList();
    }


    /**
     * 查询百度鹰眼时间断轨迹
     *
     * @throws UnsupportedEncodingException
     */
    public static YingyanHistoryVo getHistory(String entity_name, Long start_time, Long end_time)
            throws UnsupportedEncodingException {
        start_time = start_time / 1000;
        end_time = end_time / 1000;
        String sn = getHistorySn(entity_name, start_time.toString(), end_time.toString());
        StringBuilder url = new StringBuilder();
        url.append(gethistoryUrl)
                .append("ak=").append(ak).append("&service_id=").append(serviceId).append("&entity_name=")
                .append(entity_name).append("&start_time=").append(start_time).append("&end_time=")
                .append(end_time).append("&is_processed=1&transport_mode=2").append("&sn=").append(sn);
        logger.info("get鹰眼轨迹url:{}", url.toString());
        return restTemplate.getForObject(url.toString(), YingyanHistoryVo.class);
    }

    /**
     * GET请求获取sn签名
     *
     * @param entity_name
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getHistorySn(String entity_name, String start_time, String end_time)
            throws UnsupportedEncodingException {
        Map<String, String> paramsMap = new LinkedHashMap<String, String>();
        paramsMap.put("ak", ak);
        paramsMap.put("service_id", serviceId);
        paramsMap.put("entity_name", entity_name);
        paramsMap.put("start_time", start_time);
        paramsMap.put("end_time", end_time);
        paramsMap.put("is_processed", "1");
        paramsMap.put("transport_mode", "2");
        String paramsStr = toQueryString(paramsMap);
        String wholeStr = snGethistoryUrl + paramsStr + sk;
        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
        String sn = MD5(tempStr);
        logger.info("鹰眼sn签名:{}", sn);
        return sn;

    }


    /**
     * POST添加百度鹰眼entity到报百度
     *
     * @param entity_name
     * @return
     * @throws UnsupportedEncodingException
     */
    public static YingyanResVo addEntityName(String entity_name)
            throws UnsupportedEncodingException {
        logger.debug("鹰眼参数ak:{},sk:{},serviceId:{},entity_name:{}", ak, sk, serviceId, entity_name);
        Map<String, String> map = new HashMap<>();
        map.put("ak", ak);
        map.put("service_id", serviceId);
        map.put("entity_name", entity_name);
        map.put("sn", getSn(entity_name));
        return restTemplate.postForObject(addUrl, map, YingyanResVo.class);
    }

    /**
     * POST请求获取sn签名
     *
     * @param entity_name
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getSn(String entity_name)
            throws UnsupportedEncodingException {
        Map<String, String> paramsMap = new TreeMap<>();
        paramsMap.put("ak", ak);
        paramsMap.put("service_id", serviceId);
        paramsMap.put("entity_name", entity_name);
        String paramsStr = toQueryString(paramsMap);
        String wholeStr = snAddUrl + paramsStr + sk;
        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
        String sn = MD5(tempStr);
        logger.debug("鹰眼sn签名:{}", sn);
        return sn;

    }

    /**
     * 获取鹰眼sn签名专用MD5
     * 来自stackoverflow的MD5计算方法，
     * 调用了MessageDigest库函数，并把byte数组结果转换成16进制
     *
     * @param md5
     * @return
     */
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

    /**
     * 获取sn签名用
     * 对Map内所有value作utf8编码，拼接返回结果
     *
     * @param data
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8")).append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    public void setAk(String ak) {
        YingyanUtil.ak = ak;
    }

    public void setSk(String sk) {
        YingyanUtil.sk = sk;
    }

    public void setServiceId(String serviceId) {
        YingyanUtil.serviceId = serviceId;
    }

    public void setMapAk(String mapAk) {
        YingyanUtil.mapAk = mapAk;
    }

    /* entity_name="test2";
        yingyanAk="YHUrRwKknw5tkBHRwYuSTkdL7Nhq0g72";
        akMap="CsOIv1Yd0mQowBwXM5BxQuK1hl1EtTB1";
        sk="Y37rmGyIiZoa2hGTlLxbiTKMSWcKPTOs";
        serviceId="132134";
        start_time =(System.currentTimeMillis()-129600000l)/1000;
        end_time = (System.currentTimeMillis()-43200000l)/1000;*/


}
